var onConfigLoad = function () {
  "use strict";
  $('#menus .container').on('click', 'a', function (e) {
    e.preventDefault();
    window.open($(this).attr('href'));
    return false;
  });

  var Images = {
    width: 200,
    height: 130,
    defaultWidth: 1140,
    show: function (images) {
      var $container = $('#frieze .container');
      $container.html("");
      for (var i = 0; i < images.length; i++) {
        var image = images[i];
        $container.append(
          $('<div/>').addClass('frieze-image')
          .append($('<div/>').addClass('image').css({
            left: this.getLeftPosition(i, images.length, $container.width()),
            width: this.width,
            height: this.height
          }).append($('<img/>').css({
            width: image.width * image.ratio,
            height: image.height * image.ratio,
            'margin-left': image.left,
            'margin-top': image.top
          }).attr('src', image.src))));
      }
    },
    getLeftPosition: function (index, total, parentWidth) {
      parentWidth = parentWidth || this.defaultWidth;
      if (total === 1) {
        return parentWidth - this.width;
      } else {
        if (index === 0) {
          return 0;
        } else if (index === total - 1) {
          return parentWidth - this.width;
        } else {
          var gap = parseInt((parentWidth - total * this.width) / (total - 1),
            10);
          return index * (gap + this.width);
        }
      }
    }
  };

  var Menus = {
    show: function (menus) {
      var $container = $('#menus .container');
      $container.html("");
      var $menuContaier;
      var $style = $('<style/>');
      var style = "";
      style += '.menu-container .menu.custom-color { color: ' + menus.color.menu
        .textMenu;
      style += '; background-color: ' + menus.color.menu.backMenu;
      style += '; }';

      style += '.menu-container .menu.custom-color:hover { color: ' + menus.color
        .menu.textSurvol;
      style += '; background-color: ' + menus.color.menu.backSurvol;
      style += '; }';

      style += '.menu-container .menu:hover .sub-menus {display:block}';
      style += '.menu-container .menu .sub-menus {display:none}';

      style += '.menu-container .menu.custom-sub-color .sub-menu { color: ' +
        menus.color.menu.textMenu;
      style += '; background-color: ' + menus.color.subMenu.backMenu;
      style += '; }';

      style +=
        '.menu-container .menu.custom-sub-color .sub-menu:hover { color: ' +
        menus.color.menu.textSurvol;
      style += '; background-color: ' + menus.color.subMenu.backSurvol;
      style += '; }';

      $container.append($style.html(style));

      for (var i = 0; i < menus.items.length; i++) {
        var menu = menus.items[i];
        var first = false;
        if (!$menuContaier || menu.wrap) {
          if (menu.wrap && $menuContaier) {
            // remove last character
            var html = $menuContaier.html();
            $menuContaier.html(html.substring(0, html.length - 1));
          }

          var $menuRow = $('<div/>').addClass('menu-row');
          $menuRow.appendTo($container);
          $menuContaier = $('<div/>').addClass('menu-container').appendTo(
            $menuRow);
          $('<span/>').appendTo($menuRow);
          first = true;
        }

        var $menu = $('<div/>').addClass('menu');
        $menu.append($('<a/>').attr('href', menu.link).html(menu.name));

        if (menu.customMenuColor) {
          $menu.addClass('custom-color');
        }

        if (menu.customSubMenuColor) {
          $menu.addClass('custom-sub-color');
        }

        var $subMenu = $('<ul/>').addClass('sub-menus').appendTo($menu);

        for (var index = 0; index < menu.subs.length; index++) {
          $('<li/>').addClass('sub-menu')
            .append($('<a/>').attr('href', menu.subs[index].link).html(menu.subs[
              index].name))
            .appendTo($subMenu);
        }

        /*.css({
          'margin': '0 5px',
          'margin-left': first ? '0' : '5px'
        });*/

        $menu.appendTo($menuContaier);
        $menuContaier.html($menuContaier.html() + "\n");
      }

      //gadgets.window.adjustHeight($('#chronopost').height() + 20);
    }
  };

  var admin;
  var edit = function () {
    if (admin && !admin.closed) {
      return;
    }

    admin = window.open(Config.getStaticFile() + "/?domain=" + Config.getUserPref('domain') + "&site=" + Config.getUserPref('site'), '_blank',
      'toolbar=0,fullscreen=1');
    /*
    setConfigFolderInterval = setInterval(function () {
      console.log("setting config folder id.");
      admin.postMessage({
        message: 'setConfigFolderId',
        configFolderId: Config.getUserPref('config_folder')
      }, '*');
    }, 300);
    */
  };

  Config.load(function (data) {
    Images.show(data.images);
    Menus.show(data.menus);
  }, edit);

  var setConfigFolderInterval;
  window.addEventListener('message', function (event) {
    var data = event.data;
    if (!data || !data.message) {
      return;
    }

    switch (data.message) {
    case 'update':
      {
        Config.load(function (data) {
          Images.show(data.images);
          Menus.show(data.menus);
        });
        break;
      }
      /*
    case 'received':
      {
        clearInterval(setConfigFolderInterval);
        break;
      }
      */
    }
  });

  $(window).on("keypress", function (event) {
    if (event.shiftKey && event.ctrlKey && (event.charCode === 47 || event.charCode ===
      63)) {
      edit();
    }
  });

  //gadgets.window.adjustHeight(500);
};

$(function () {
  var interval = setInterval(function () {
    if (window.Config) {
      onConfigLoad();
      clearInterval(interval);
    }
  }, 50);
});
